#include "an.h"
#include "../gui.window.h"
#include "../gui.text.h"
#include "../gui.button.h"

TOB::UI_AN::UI_AN(UIConfig &c): Mod(c) {
  anClient = 0;
}

TOB::UI_AN::~UI_AN() {
  if(anClient) {
    delete anClient;
  }
}

void TOB::UI_AN::run() {
  // Create objects
  bool accepted = false;
  String temp;
  UIWindow ANw(0, 0, 15, 5);
  UIText usernamet(16, 2, 15, 4); 
  UIText passwordt(16, 4, 15, 4);
  UIButton loginb(16, 6, 15, 4);
  UIWindow alert(16, 0, 0, 0);

  // Set attributes
  passwordt.password = true;
  loginb.title = config.lang["log-in"];

  // Bind events
  usernamet.eventReturn = usernamet.eventTab = [&]() {
    usernamet.running = false;
    passwordt.focus();
  };
  passwordt.eventReturn = passwordt.eventTab = [&]() {
    passwordt.running = false;
    loginb.focus();
  };
  loginb.eventTab = [&]() {
    loginb.running = false;
    loginb.print();
    usernamet.focus();
  };

  // Connector
  loginb.eventClick = [&]() {
    if(config.ns.requestAddress(Server::Authentication, anip) != Code::Okay) {
      alert.setCursor(0, 0);
      alert.clearLine();
      alert.putString(config.lang["ns-doesnt-respond"]);
      return;
    } 

    anClient = new AN::Client(
          anip, 
          CONVERT(usernamet.lines[0]), 
          CONVERT(passwordt.lines[0])
        );

    Code::Type code = anClient->login();
    if(code != Code::Okay) {
      alert.setCursor(0, 0);
      alert.clearLine();
      alert.putString(
          (code == Code::AN_PasswordUncorrect || code == Code::US_DataFetchError) ?
          config.lang["wrong-up-pair"] :
          (code == Code::AN_DoesntRespond) ?
          config.lang["an-doesnt-respond"] :
          config.lang["us-doesnt-respond"]);
      delete anClient;
      return;
    }

    accepted = true;
  };

  // Labels
  temp = config.lang["username"];
  ANw.setCursor(1, 2);
  ANw.putString(temp);
  temp = config.lang["password"];
  ANw.setCursor(1, 4);
  ANw.putString(temp);

  // Start
  while(!accepted) {
    loginb.print();
    usernamet.focus();
  }
  config.username = CONVERT(usernamet.lines[0]);
  config.password = CONVERT(passwordt.lines[0]);

  // Dispose
  ANw.dispose();
  usernamet.dispose();
  passwordt.dispose();
  loginb.dispose();
}
